<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Coupon as ModelCoupon;
use app\common\model\coupon\Log;
use ErrorException;
use think\Db;

/**
 * 优惠券接口
 */
class Coupon extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 优惠券列表
     *
     */
    public function list()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || empty($type)) {
            $this->error('参数错误');
        }
        $coupon = new ModelCoupon;
        $couponLog = new Log();
        $ids =  $couponLog->where('user_id', $this->auth->id)->column('coupon_id');
        $list = $coupon->whereNotIn('id', $ids)->where('type', $type)->paginate(10);
        $this->success('请求成功', $list);
    }

    /**
     * 优惠券领取
     *
     */
    public function receive()
    {
        $post = request()->post();
        extract($post);
        // if (!isset($ids) || empty($ids)) {
        //     $this->error('参数错误');
        // }
        Db::startTrans();
        try {
            $coupon = new ModelCoupon;
            if (isset($ids) && !empty($ids)) {
                $coupon->where('id', $ids);
            }
            $list = collection($coupon->select())->toArray();
            foreach ($list as &$v) {
                $v['user_id'] = $this->auth->id;
                $v['type'] = 1;
                $v['coupon_id'] = $v['id'];
                $workrange = explode(' - ', $v['workrange']);
                unset($v['id']);
                unset($v['workrange']);
                $v['startdate'] = $workrange[0];
                $v['enddate'] = $workrange[1];
                $check = Log::where('user_id', $this->auth->id)->where('coupon_id', $v['coupon_id'])->count();
                if ($check) {
                    throw new ErrorException('【' . $v['name'] . '】优惠券已领取');
                }
                $couponLog = new Log();
                $couponLog->allowField(true)->save($v);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('领取失败:' . $e->getMessage());
        }
        $this->success('领取成功');
    }

    /**
     * 我的优惠券
     *
     */
    public function my_coupon()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        $user_id =  $this->auth->id;
        //更新过期优惠券
        Log::editState($user_id);
        $couponLog = new Log();
        $couponLog->where('user_id', $user_id);
        if ($type == 1) {
            $couponLog->where('state', 1);
        } else {
            $couponLog->whereIn('state', [0, 2]);
        }
        $list =  $couponLog->order('createtime desc')->paginate(10);
        $this->success('请求成功', $list);
    }
}
